package cn.js.sangu.unitStore.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.js.sangu.unitStore.common.LogType;
import cn.js.sangu.unitStore.common.MyAuthAccess;
import cn.js.sangu.unitStore.common.MyLogsAOP;
import cn.js.sangu.unitStore.common.R;
import cn.js.sangu.unitStore.common.exception.ServiceException;
import cn.js.sangu.unitStore.entity.ProjectPro;
import cn.js.sangu.unitStore.entity.ProjectProActivity;
import cn.js.sangu.unitStore.entity.User;
import cn.js.sangu.unitStore.service.ProcessNodeService;
import cn.js.sangu.unitStore.service.ProjectProActivityService;
import cn.js.sangu.unitStore.service.ProjectProService;
import cn.js.sangu.unitStore.service.UserService;
import lombok.extern.slf4j.Slf4j;

/**
 * 说明：项目进度接口
 * 作者：linshuo
 * 日期：2024/8/7 8:40
 */
// @CrossOrigin //已有全局跨域设置CorsConfig
@RequestMapping("projectPro")
@RestController
@Slf4j
public class ProjectProController {

    static final String OPERATION_PROJECT = "项目进度";

    @Autowired
    ProjectProService projectProService;

    @Autowired
    ProcessNodeService processNodeService;

    @Autowired
    UserService userService;

    @Autowired
    ProjectProActivityService projectProActivityService;

    @MyLogsAOP(operation = OPERATION_PROJECT, operaType = LogType.LOOKUP)
    @GetMapping("findByPage")
    public R findByPage(@RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam String projectName,
            @RequestParam String creator,
            @RequestParam String recipient) {
        QueryWrapper<ProjectPro> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(projectName), "project_name", projectName);
        wrapper.eq(StrUtil.isNotBlank(creator), "creator", creator);
        wrapper.like(StrUtil.isNotBlank(recipient), "recipient", recipient);
        wrapper.orderByDesc("id");
        // 构建page对象
        Page<ProjectPro> param = new Page<>(pageNum, pageSize);
        Page<ProjectPro> res = projectProService.page(param, wrapper);

        // 补充项目相关人员名称
        List<ProjectPro> records = suppleName(res.getRecords());
        return R.ok(res.setRecords(records));
    }

    @MyLogsAOP(operation = OPERATION_PROJECT, operaType = LogType.ADD)
    @RequestMapping("save")
    public R save(@RequestBody ProjectPro dto) {
        if (dto.getCurrentStep() == null) {
            throw new ServiceException("步骤参数不存在");
        }
        ProjectPro projectPro = projectProService.saveInfo(dto);
        return R.ok("《" + projectPro.getProjectName() + "》保存成功");
    }

    @MyLogsAOP(operation = OPERATION_PROJECT, operaType = LogType.UPDATE)
    @PutMapping("update")
    public R update(@RequestBody ProjectPro dto) {
        projectProService.updateInfo(dto);
        return R.ok("修改成功");
    }

    @MyLogsAOP(operation = OPERATION_PROJECT, operaType = LogType.DELETE)
    @DeleteMapping("delete/{id}")
    public R delete(@PathVariable Integer id) {
        projectProService.removeById(id);
        return R.ok("删除成功");
    }

    @MyLogsAOP(operation = OPERATION_PROJECT, operaType = LogType.BATCH_DELETE)
    @DeleteMapping("deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        projectProService.removeBatchByIds(ids);
        return R.ok("批量删除成功");
    }

    // @MyLogsAOP(operation = OPERATION_PROJECTUMENT,operaType = LogType.LOOKUP)
    @MyAuthAccess
    @GetMapping("findById/{id}")
    public R findById(@PathVariable Integer id) {
        ProjectPro projectPro = projectProService.getById(id);
        User user = userService.getById(projectPro.getCreator());
        if (null != user) {
            projectPro.setCreatorName(user.getName());
        }
        return R.ok(projectPro);
    }

    // @MyLogsAOP(operation = OPERATION_PROJECTUMENT,operaType = LogType.LOOKUP)
    @GetMapping("findByRecent")
    public R findByRecent() {
        LambdaQueryWrapper<ProjectPro> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(ProjectPro::getCreatTime).last("LIMIT 10");
        return R.ok(suppleName(projectProService.list(wrapper)));
    }

    /**
     * 补充创建人+修改人+接收人 名称
     * 
     * @param list
     * @return
     */
    private List<ProjectPro> suppleName(List<ProjectPro> list) {
        for (ProjectPro projectPro : list) {
            // 创建人
            User author = userService.getById(projectPro.getCreator());
            if (null != author)
                projectPro.setCreatorName(author.getName());
            // 修改人
            User modifier = userService.getById(projectPro.getModifier());
            if (null != modifier)
                projectPro.setModifierName(modifier.getName());
            // 接收人
            User recipient = userService.getById(projectPro.getRecipient());
            if (null != recipient)
                projectPro.setRecipientName(recipient.getName());
            // 审核人
            User auditor = userService.getById(projectPro.getAuditor());
            if (null != auditor)
                projectPro.setAuditorName(auditor.getName());
        }
        return list;
    }

    /**
     * 获取项目活动记录
     * 
     * @param projectId 项目ID
     * @return 活动记录列表
     */
    @GetMapping("getActivities")
    public R getActivities(Integer projectId) {
        if (projectId == null) {
            return R.fail("项目ID不能为空");
        }

        // 获取项目信息
        ProjectPro projectPro = projectProService.getById(projectId);
        if (projectPro == null) {
            return R.fail("未找到项目信息");
        }

        try {
            // 根据项目ID从ProjectProActivityService获取所有关联记录，并按时间倒序排序
            LambdaQueryWrapper<ProjectProActivity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ProjectProActivity::getProId, projectId)
                    .orderByAsc(ProjectProActivity::getCreatTime);

            List<ProjectProActivity> projectActivities = projectProActivityService.list(queryWrapper);

            // 构建前端需要的活动记录列表
            List<Map<String, Object>> activities = new ArrayList<>();
            if (projectActivities != null && !projectActivities.isEmpty()) {
                for (ProjectProActivity activity : projectActivities) {
                    Map<String, Object> activityMap = new HashMap<>();
                    // 设置前端所需的字段
                    if (activity.getIsPass() == null) {
                        activityMap.put("type", "primary");
                        activityMap.put("icon", "el-icon-circle-plus-outline");
                    } else if (activity.getIsPass()) {
                        activityMap.put("type", "success");
                        activityMap.put("icon", "el-icon-circle-check");
                    } else {
                        activityMap.put("type", "danger");
                        activityMap.put("icon", "el-icon-circle-close");
                    }
                    activityMap.put("size", "small");
                    // 使用Hutool的DateUtil将时间格式化为年月日时分秒格式
                    activityMap.put("timestamp",
                            activity.getCreatTime() != null
                                    ? DateUtil.format(activity.getCreatTime(), "yyyy-MM-dd HH:mm:ss")
                                    : "");
                    activityMap.put("title", activity.getStepName() != null ? activity.getStepName() : "未命名步骤");
                    activityMap.put("description", activity.getDescription() != null ? activity.getDescription() : "");
                    activityMap.put("handler", activity.getHandlerName() != null ? activity.getHandlerName() : "未知");

                    activities.add(activityMap);
                }
            }

            return R.ok(activities);
        } catch (Exception e) {
            log.error("获取项目活动记录失败: {}", e.getMessage());
            return R.fail("获取活动记录失败: " + e.getMessage());
        }
    }

}
